//
//  ZCAddressListVC.m
//  ZCJZ
//
//  Created by sujeking on 2019/2/27.
//  Copyright © 2019年 jeking. All rights reserved.
//

#import "WZGAddressListVC.h"

#import "ZCAddNewAddressVC.h"
#import "ZCAddressViewModel.h"
#import "ZCAddressListCell.h"
#import "ZCOrderListBodySearchView.h"

@interface WZGAddressListVC ()
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIView *barview;
@property (weak, nonatomic) IBOutlet UIButton *addBtn;

@property (nonatomic, copy) NSArray *list;
@property (nonatomic, copy) NSDictionary *selectedDict;
@property (nonatomic, assign) bool isDeleted ;

@end

@implementation WZGAddressListVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self netFetchMyAddressList:nil];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
}

- (void)basePopAction{
    if (self.addressSelectedCallBack) {
        self.addressSelectedCallBack(self.selectedDict,self.isDeleted);
    }
    [super basePopAction];
}

- (void)setupUI {
    self.navTitle = @"地址列表";
    self.tableView.dataSource = self;
    self.tableView.delegate = self;

    self.barview.layer.shadowColor = [UIColor grayColor].CGColor;
    self.barview.layer.shadowOffset = CGSizeMake(0, -2);
    self.barview.layer.shadowOpacity = 0.5;
    
    UIImage *img = [UIImage imageNamed:@"addBtn_redBtn"];
    [self.addBtn setImage:img forState:UIControlStateNormal];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"ZCAddressListCell" bundle:nil] forCellReuseIdentifier:@"ZCAddressListCell"];
    
    ZCOrderListBodySearchView *view = [[ZCOrderListBodySearchView alloc] initWithFlex:nil Frame:(CGRect){0,0,[UIScreen mainScreen].bounds.size.width,40} Owner:nil];
    UIView *headerView = [[UIView alloc] initWithFrame:(CGRect){0,0,[UIScreen mainScreen].bounds.size.width,40}];
    view.placehstr = @"姓名/电话/地址";
    view.frame = headerView.bounds;
    __weak typeof(self) weakSelf = self;
    [view setEndEditCallback:^(NSString *keywd) {
        [weakSelf netFetchMyAddressList:keywd];
    }];
    [headerView addSubview:view];
    self.tableView.tableHeaderView = headerView;
    
//    [self setTableView:self.tableView noDataWithTitle:@"暂无地址,马上添加一个吧" des:nil andImageName:nil];
}

// MARK: - UITableViewDelegate,UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.list.count;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger row = indexPath.row;
    ZCAddressListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ZCAddressListCell"
                                                               forIndexPath:indexPath];
    cell.dict = self.list[row];
    cell.canselect = self.canselect;
    __weak typeof(self) weakSelf = self;
    [cell setEditBtnClickCallBack:^(NSDictionary * _Nonnull dict) {
        [weakSelf editAddtessWithDict:dict];
    }];
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    return 60.0f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewAutomaticDimension;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.01f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger row = indexPath.row;
    self.selectedDict = self.list[row];
    if (self.addressSelectedCallBack) {
        self.addressSelectedCallBack(self.selectedDict,NO);
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger row = indexPath.row;
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        __block NSDictionary *dict = self.list[row];
        __weak typeof(self) weakSelf = self;
        [self showAlert:@"提示" content:@"确定删除该条地址吗?" actionStr1:@"删除" style:UIAlertActionStyleDestructive actionAc1:^(UIAlertAction * _Nonnull action) {
            [weakSelf  netRemoveAddressWithDict:dict];
        } actionStr2:@"取消" style:UIAlertActionStyleCancel actionAc:^(UIAlertAction * _Nonnull action) {
            
        }];
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
    return @"删除";
}

- (IBAction)addAddressBtnClickAction:(id)sender {
    ZCAddNewAddressVC *vc = [[ZCAddNewAddressVC alloc] init];
    vc.isNormal = self.isNormal;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)editAddtessWithDict:(NSDictionary *)dict {
    ZCAddNewAddressVC *vc = [[ZCAddNewAddressVC alloc] init];
    vc.isNormal = self.isNormal;
    vc.dict = dict;
    WeakSelf(self);
    [vc setEditCallback:^(NSDictionary *dict){
        weakself.isDeleted = NO;
        weakself.selectedDict = dict;
    }];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)selectRowWithIndex:(NSInteger)index {
    NSIndexPath *path = [NSIndexPath indexPathForRow:index inSection:0];
    [self.tableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionNone];
}

// MARK: - SET

- (void)setParams:(NSDictionary *)params {
  [super setParams:params];
  self.isNormal = [[params valueForKey:@"isNormal"] boolValue];
}

// MARK: - NET

- (void)netFetchMyAddressList:(NSString *)kw {
    __weak typeof(self) weakSelf = self;
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [ZCAddressViewModel fetchMyAddressListWithKeywords:kw complete:^(ZCErrorCode status, NSString *message, id data) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        if (status == kHXSInvalidTokenError) {
//            WZGLoginVC *vc = [[WZGLoginVC alloc] init];
//            [vc setGoodsVCCallBack:^(NSInteger type) {
//                if (type == 0) {
//                    [weakSelf.navigationController popViewControllerAnimated:YES];
//                } else {
//                    [weakSelf.tableView.mj_header beginRefreshing];
//                }
//            }];
//            UINavigationController *nvc = [[UINavigationController alloc] initWithRootViewController:vc];
//            nvc.modalPresentationStyle = UIModalPresentationFullScreen;
//            [weakSelf.navigationController presentViewController:nvc animated:YES completion:nil];
        } else if (status == kHXSNoError) {
            [weakSelf hiddenNodataView];
            weakSelf.list = [data valueForKey:@"items"];
            
            for (NSDictionary *dict in weakSelf.list) {
                if([[dict valueForKey:@"is_default"] boolValue]) {
                    weakSelf.selectedDict = dict;
                    break;
                }
            }
            
            [self.tableView reloadData];
            for (NSDictionary *dict in weakSelf.list) {
                if ([[dict valueForKey:@"is_default"] boolValue]) {
                    NSInteger index = [weakSelf.list indexOfObject:dict];
                    [weakSelf selectRowWithIndex:index];
                }
            }
        } else {
            [weakSelf.view makeToast:message duration:2.0 position:CSToastPositionCenter];
        }
    }];
}

- (void)netRemoveAddressWithDict:(NSDictionary *)dict {
    __weak typeof(self) weakSelf = self;
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [ZCAddressViewModel removeAddressWithDict:dict complete:^(ZCErrorCode status, NSString *message, id data) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        if (status == kHXSNoError) {
            weakSelf.isDeleted = YES;
            [weakSelf.view makeToast:@"操作成功" duration:1.0 position:CSToastPositionCenter];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakSelf netFetchMyAddressList:nil];
            });
        } else {
            [weakSelf.view makeToast:message duration:2.0 position:CSToastPositionCenter];
        }
    }];
}
@end
